﻿using System.Collections.Generic;
using System.Linq;
using Rhizome.Contract;
using Rhizome.Contract.Diag;
using Rhizome.Contract.Visitor;
using Rhizome.Model.Visitor;

namespace Rhizome.Model.Validation
{
	/// <summary>
	/// Validates Automaton definition. Collects all exceptions
	/// </summary>
	public static class ElementExtention
	{
		/// <summary>
		/// Validates specific element with sub elements
		/// </summary>
		/// <param name="root">root element to validate</param>
		/// <returns>validation results</returns>
		public static IEnumerable<ValidationResultList> GetAllValidationResults(this IElement root)
		{
			return 
				from e in root.GetAllElements<IValidate>() 
				let results = e.GetValidationResults().ToList() 
				where results.Any() 
				select new ValidationResultList(e, results);
		}

		public static void Validate(this IElement root)
		{
			var results =
				from l in root.GetAllValidationResults()
				from r in l.Results
				where (r.Severity & ValidationSeverity.Error) != 0
				select r;

			var m = results.FirstOrDefault();

			if (m != null) 
				throw new ValidationException(m.Message);
		}
	}
}